import { useStore } from '@/hooks';
import * as api_account from '@/services/account';
import { Button, Form, Input, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useState } from 'react';
import { useHistory } from 'react-router';
import styles from './LoginBlock.module.scss';
import { useInterval } from './utils';
import setLogin from '../../../../assets/setlogin.png';

const { Item } = Form;
const DEFAULT_DATA = {
  name: '',
  password: '',
  autoLogin: true,
  phone: '',
  code: '',
};

const layout = {
  height: 45,
};
const LoginBlock = (
  props = {
    dataSource: DEFAULT_DATA,
  },
) => {
  const { loginStore } = useStore();
  const { dataSource = DEFAULT_DATA } = props;
  const [postData, setValue] = useState(dataSource);
  const [isRunning, checkRunning] = useState(false);
  const [second, setSecond] = useState(59);
  const [loading, setLoading] = useState(false);
  const [code, setCode] = useState({
    captcha: '',
    captchaKey: '',
  });
  const history = useHistory();
  useInterval(
    () => {
      setSecond(second - 1);

      if (second <= 0) {
        checkRunning(false);
        setSecond(59);
      }
    },
    isRunning ? 1000 : null,
  );

  const formChange = (values) => {
    setValue(values);
  };
  React.useEffect(() => {
    api_account.authCode().then((x) => {
      setCode(x);
    });
  }, []);

  const handleSubmit = (values, errors) => {
    if (errors) {
      return;
    }
    setLoading(true);
    loginStore
      .auth({
        ...values,
        username: `${values.username}@${TENANT}`,
        captchaKey: code.captchaKey,
        captchaCode: values.captchaCode,
      })
      .then((_) => {
        Message.success(t`登录成功!`);
        setLoading(false);
        window.location.reload();
      })
      .catch((err) => {
        changeImg();
        setLoading(false);
        let errTip = '';
        const { source } = err;
        switch (source?.code) {
          case 10400:
            errTip = t`无效的验证码`;
            break;
          default:
            if (source?.code === 10401 && source?.message === 'User disabled.') {
              errTip = t`公司被禁用`;
            } else if (source?.code === 10401 && source?.message === 'Invalid credential.') {
              errTip = t`密码错误`;
            } else if (source?.code === 10401 && source?.message === 'User not found.') {
              errTip = t`用户不存在`;
            } else {
              errTip = t`登录失败`;
            }
            break;
        }
        Message.warning(errTip);
      });
  };

  const changeImg = () => {
    api_account.authCode().then((x) => {
      setCode(x);
    });
  };
  const accountForm = (
    <>
      <Item required requiredMessage="必填" style={layout}>
        <Input name="username" placeholder={t`用户名`} />
      </Item>
      <Item required requiredMessage="必填" style={layout}>
        <Input.Password name="password" htmlType="password" placeholder={t`密码`} />
      </Item>
      <div style={{ display: 'flex', justifyContent: 'space-between' }}>
        <Item required requiredMessage="必填" style={layout}>
          <Input name="captchaCode" placeholder={t`验证码`} />
        </Item>
        <img src={code.captcha} height={40} alt={t`验证码`} style={{ cursor: 'pointer' }} onClick={changeImg} />
      </div>
    </>
  );

  return (
    <div>
      <div className={styles.innerBlock}>
        <div
          style={{ color: '#126be9', fontWeight: 'bold', fontSize: 24, textAlign: 'center', margin: 20 }}
        >{t`用户登录`}
        </div>
        <Form value={postData} onChange={formChange} size="large">
          {accountForm}

          <div className={styles.infoLine}>
            <Item
              style={{
                marginBottom: 10,
              }}
            />
          </div>

          <div style={{ marginBottom: 10 }}>
            <img style={{ width: '18px', marginRight: '3px', marginBottom: -5 }} src={setLogin} alt="" />
            <span>调度员请<Button text type="primary" style={{ marginBottom: 2 }} onClick={() => history.push('/user/phoneLogin')}>点击这里</Button>，用手机验证码登录</span>
          </div>

          <Item
            style={{
              marginBottom: 10,
            }}
          >
            <Form.Submit
              loading={loading}
              type="primary"
              htmlType="submit"
              onClick={handleSubmit}
              className={styles.submitBtn}
              validate
            >
              {t`登录`}
            </Form.Submit>
          </Item>
        </Form>
      </div>
    </div>
  );
};

export default LoginBlock;
